﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetCoreApi.Filter
{
    public class ResultFilter : Attribute, IResultFilter
    {

        private ReturnJson Success()
        {
            return new ReturnJson().Success();
        }
        private ReturnJson Success<T>(T t)
        {
            return new ReturnJson<T>().Success(t);
        }
        private ReturnJson Fail()
        {
            return new ReturnJson().Fail();
        }
        private ReturnJson Null()
        {
            return new ReturnJson().Null();
        }
        /// <summary>
        /// 结果返回前
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is EmptyResult a)
            {
                if (a == null)
                {
                    context.Result = new JsonResult(Null());
                }
                context.Result = new JsonResult(Success());

            }
            else if (context.Result is ObjectResult b)
            {
                if (b.Value is bool c)
                {
                    if (!c)
                    {
                        context.Result = new JsonResult(Fail());
                    }
                    else
                    {
                        context.Result = new JsonResult(Success());
                    }
                }
                else
                {
                    context.Result =  new JsonResult(Success(b.Value));
                }
            }
        }
        /// <summary>
        /// 结果返回
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {

        }
    }
}
